// 注册app
const Koa = require('koa')
const app = new Koa()

const path = require('path')


//解决跨域
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*')
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, DELETE')
  await next()
})

// 05koa2_demo表单
// 对于POST请求的处理，koa-bodyparser中间件可以把koa2上下文的formData数据解析到ctx.request.body中
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

// koa-static开发静态资源目录
// const static = require('koa-static')
// const staticPath = './static'
// app.use(static(
//   path.join(__dirname, staticPath)
// ))

// koa2模板引擎
const views = require('koa-views')
app.use(views(path.join(__dirname, './views'), {
  extension: 'ejs'
}))
app.use(async (ctx, next) => {
  let title = 'hello koa2 views'
  await ctx.render('index', {
    title
  })
})

// koa上传功能之busboy模块


// 原始路由中间件 '/'
// app.use(async (ctx, next) => {
//   ctx.body = 'hello koa2'
//   await next()
// })

// koa-router
const Router = require('koa-router')
//子路由1
let home = new Router()
home.get('/home', async (ctx, next) => {
  ctx.body = 'home page'
  await next()
})
// 子路由2
let form = new Router()
home.post('/form', async (ctx, next) => {
  ctx.body = ctx.request.body
  await next()
})
// 子路由3 cookie
let cid = new Router()
cid.get('/cid', async (ctx, next) => {
  ctx.cookies.set(
    'cid',
    '001', 
    {
      domain: '127.0.0.1',  // 写cookie所在的域名 注意一致
      path: '/cid',       // 写cookie所在的路径   注意一致
      maxAge: 10 * 60 * 1000, // cookie有效时长
      expires: new Date('2023-02-15'),  // cookie失效时间
      httpOnly: true,  // 是否只用于http请求中获取 仅服务端获取
      overwrite: false,  // 是否允许重写
      sameSite: 'lax',  //解决samesite问题
    }
  )
  ctx.body = 'cookie set ok'
})
// 装载所有子路由
let router = new Router()
router.use('/api', home.routes(), home.allowedMethods())
router.use('/api', form.routes(), form.allowedMethods())
router.use('/api', cid.routes(), cid.allowedMethods())
// 加载路由中间件
app.use(router.routes())
app.use(router.allowedMethods())

//监听端口
app.listen(3000, () => {
  console.log('服务器运行在http://127.0.0.1:3000')
})